<template>
  <div>
    <el-form ref="dynamicValidateForm" :model="dynamicValidateForm" label-width="150px" class="demo-dynamic">
      <el-form-item prop="code" label="存款账户" :rules="[
          { required: true, message: '请输入16到20位的存款账户', trigger: 'blur', min: 16, max: 20 }
        ]">
        <el-input v-model="dynamicValidateForm.code" />
      </el-form-item>
      <el-form-item prop="money" label="存款金额(元)" :rules="[
          { required: true, pattern: /^([1-9]\d{0,9}|0)(\.\d{1,2})?$/, message: '请输入取款金额(可包含2位小数)', trigger: 'blur' }
        ]">
        <el-input v-model="dynamicValidateForm.money" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
        <el-button @click="resetForm('dynamicValidateForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { saveMoney } from '@/api/api'

export default {
  data() {
    return {
      dynamicValidateForm: {
        code: '',
        money: ''
      }
    }
  },
  methods: {
    submitForm(dynamicValidateForm) {
      this.$refs[dynamicValidateForm].validate((valid) => {
        if (valid) {
          console.log(this.dynamicValidateForm.code, this.dynamicValidateForm.money)
          saveMoney({
            'bankCard': this.dynamicValidateForm.code,
            'currentBalance': this.dynamicValidateForm.money
          }).then(res => {
            console.log(res, 'res')
            if (res.data.responseStatusCode == 200) {
              this.$message({
                showClose: true,
                message: res.data.message,
                type: 'success'
              })
              this.dynamicValidateForm.code = '',
                this.dynamicValidateForm.money = ''
            } else if (res.data.responseStatusCode == 408) {
              localStorage.removeItem('token')
              localStorage.removeItem('role')
              localStorage.removeItem('username')
              localStorage.removeItem('bankCard')
              this.$router.push(`/login?redirect=${this.$route.fullPath}`)
              this.$message({
                showClose: true,
                message: res.data.message,
                type: 'error'
              })
            } else {
              this.$message({
                showClose: true,
                message: res.data.message || '存款失败，请刷新页面！',
                type: 'error'
              })
              this.dynamicValidateForm.code = '',
                this.dynamicValidateForm.money = ''
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(dynamicValidateForm) {
      this.$refs[dynamicValidateForm].resetFields()
    }
  }
}

</script>

<style scoped>
.demo-dynamic {
  margin-top: 50px;
  width: 500px;
}
</style>
